package edu.gatech.asthma.activity;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.GregorianCalendar;
import java.util.Locale;

import edu.gatech.asthma.R;
import edu.gatech.asthma.ui_support.HelpMenuHelper;
import edu.gatech.asthma.ui_support.ScheduleAdapter;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

/**
 * Activity that allows user to view calendar and upcoming events
 */
public class ScheduleActivity extends Activity {

	public ArrayList<String> items; // container to store calendar items which needs showing the event marker
	public GregorianCalendar month, itemMonth; // calendar instances
	public Handler handler; // grabs some event values to show dot marker
	public ScheduleAdapter adapter; // adapter instance
	int identifier = -1;	//used to uniquely identify current user in database
	

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.calendar);
		 Locale.setDefault( Locale.US );
		month = (GregorianCalendar) GregorianCalendar.getInstance();
		itemMonth = (GregorianCalendar) month.clone();

		items = new ArrayList<String>();
		adapter = new ScheduleAdapter(this, month);

		GridView gridview = (GridView) findViewById(R.id.gridview);
		gridview.setAdapter(adapter);

		handler = new Handler();
		handler.post(calendarUpdater);
		
		// identifier used to identify current profile user (should be passed with all intents)
		Bundle extras = getIntent().getExtras();
        if (extras != null) {
        	identifier = extras.getInt("ID");
        }

		TextView title = (TextView) findViewById(R.id.title);
		title.setText(android.text.format.DateFormat.format("MMMM yyyy", month));

		RelativeLayout previous = (RelativeLayout) findViewById(R.id.previous);

		previous.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				setPreviousMonth();
				refreshCalendar();
			}
		});

		RelativeLayout next = (RelativeLayout) findViewById(R.id.next);
		next.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				setNextMonth();
				refreshCalendar();

			}
		});

		gridview.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View v,
					int position, long id) {

				((ScheduleAdapter) parent.getAdapter()).setSelected(v);
				String selectedGridDate = ScheduleAdapter.dayString
						.get(position);
				String[] separatedTime = selectedGridDate.split("-");
				String gridvalueString = separatedTime[2].replaceFirst("^0*",
						"");
				int gridvalue = Integer.parseInt(gridvalueString);
				// clicking offdays takes user to appropriate month 
				if ((gridvalue > 10) && (position < 8)) {
					setPreviousMonth();
					refreshCalendar();
				} else if ((gridvalue < 7) && (position > 28)) {
					setNextMonth();
					refreshCalendar();
				}
				((ScheduleAdapter) parent.getAdapter()).setSelected(v);

				showToast(selectedGridDate);

			}
		});
	}

	/**
	 * Sets the next moth n the calendar
	 */
	protected void setNextMonth() {
		if (month.get(GregorianCalendar.MONTH) == month
				.getActualMaximum(GregorianCalendar.MONTH)) {
			month.set((month.get(GregorianCalendar.YEAR) + 1),
					month.getActualMinimum(GregorianCalendar.MONTH), 1);
		} else {
			month.set(GregorianCalendar.MONTH,
					month.get(GregorianCalendar.MONTH) + 1);
		}

	}
	
	/**
	 * Sets the previous moth n the calendar
	 */
	protected void setPreviousMonth() {
		if (month.get(GregorianCalendar.MONTH) == month
				.getActualMinimum(GregorianCalendar.MONTH)) {
			month.set((month.get(GregorianCalendar.YEAR) - 1),
					month.getActualMaximum(GregorianCalendar.MONTH), 1);
		} else {
			month.set(GregorianCalendar.MONTH,
					month.get(GregorianCalendar.MONTH) - 1);
		}

	}

	/**
	 * Displays a small pop up to the user
	 */
	protected void showToast(String string) {
		Toast.makeText(this, string, Toast.LENGTH_SHORT).show();

	}

	/**
	 * Updates the calandar view
	 */
	public void refreshCalendar() {
		TextView title = (TextView) findViewById(R.id.title);

		adapter.refreshDays();
		adapter.notifyDataSetChanged();
		handler.post(calendarUpdater); // generates calendar items

		title.setText(android.text.format.DateFormat.format("MMMM yyyy", month));
	}

	public Runnable calendarUpdater = new Runnable() {

		@Override
		public void run() {
			items.clear();

			// prints the dates of current week
			DateFormat df = new SimpleDateFormat("yyyy-MM-dd",Locale.US);
			@SuppressWarnings("unused")
			String itemvalue;
			for (int i = 0; i < 7; i++) {
				itemvalue = df.format(itemMonth.getTime());
				itemMonth.add(GregorianCalendar.DATE, 1);
				// temporary event examples
				items.add("2014-03-10");
				items.add("2014-04-05");
				items.add("2014-04-17");
				items.add("2014-04-20");
				items.add("2014-05-14");
				items.add("2014-05-16");
			}

			adapter.setItems(items);
			adapter.notifyDataSetChanged();
		}
	};
	
	/**
	 * User clicked the help button on this screen
	 * @param v ImageView clicked
	 */
	public void helpButtonClicked(View v) {
		HelpMenuHelper.displayHelpMessage(this);
	}
}
